# -*- coding: utf-8 -*-


import sys
sys.path.insert(0, 'lib/weibopy.zip')
sys.path.append('lib/weibopy.zip/weibopy')

import weiboActions
import weiboAuth

from google.appengine.api import xmpp
from google.appengine.ext import webapp,db
from google.appengine.ext.webapp.util import run_wsgi_app

class XMPPHandler(webapp.RequestHandler):
    def __init__(self):
        self.auth = weiboAuth.weiboAuth()
        self.weiboActions = weiboActions.weiboActions()
        self.token = None

    def post(self):
        message = xmpp.Message(self.request.POST)
        msg = message.body
        command = msg[0]
        body = msg[1:].strip()
        if(command=='r'):
            message.reply(u"请访问以下地址并记录密钥，以便给予应用授权"
                            +  self.auth.get_sina_token()
                            + u"\n 请输入a+密钥注册！")
        if(command=='a'):
            self.auth.access_auth(body,self.token[1])
            message.reply(u"机器人可以工作了！")
        if(command=='w'):
            retval = publish_sina_weibo(body)
            message.reply(u"微博发布成功："+ retval)

application = webapp.WSGIApplication([('/_ah/xmpp/message/chat/', XMPPHandler)],
    debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()